package com.medvalley.tcm.controller;

import com.alibaba.fastjson.JSON;
import com.medvalley.tcm.base.BusinessException;
import com.medvalley.tcm.base.Result;
import com.medvalley.tcm.service.SMSService;
import com.medvalley.tcm.service.SickInfoStorageService;
import com.medvalley.tcm.service.impl.AliOSSService;
import com.medvalley.tcm.utils.AESUtil;
import com.medvalley.tcm.utils.EncryptUtils;
import com.medvalley.tcm.vo.inputvo.SickInfoStorageInputVo;
import com.medvalley.tcm.vo.outputvo.SickInfoStorageOutputVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @author linsong
 * @date 2019/7/21 11:29
 **/

@RestController
@RequestMapping("/storage")
public class SickInfoStorageController extends BaseController {
    private static Logger LOGGER = LoggerFactory.getLogger(SickInfoStorageController.class);

    @Autowired
    private SickInfoStorageService sickInfoStorageService;

    @Value("${oss.sick_info.bucketName}")
    private String storageBucketName;

    @Value("${aes.key}")
    private String aesKey;


    @Autowired
    private AliOSSService aliOSSService;

    @Autowired
    private SMSService smsService;

    @GetMapping("/getsmscode")
    public String getSmsCode(@RequestParam String callback, @RequestParam String phone) {
        String returnMsg = callback + "(";
        try {
            Result result = success();
            if (sickInfoStorageService.listByPhone(phone).size() == 0) {
                result.setData("该手机当前无报告");
            } else {
                smsService.sendSms(phone, "SMS_171187926");
                result.setData("短信验证码已发送");
            }
            returnMsg = returnMsg + JSON.toJSONString(result) + ")";
        } catch (Exception e) {
            LOGGER.error(" get sms code error,phone:{}", phone, e);
            returnMsg = returnMsg + JSON.toJSONString(error("服务器错误")) + ")";
        }
        return returnMsg;
    }

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam String barcode, @RequestParam String phone, @RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String suffix = "";
        if (fileName.lastIndexOf(".") > 0) {
            suffix = fileName.substring(fileName.lastIndexOf("."));
        }
        long currentTime = System.currentTimeMillis();
        try {
            String uri = aliOSSService.upload(file.getInputStream(), phone + "-" + currentTime + suffix, storageBucketName);
            SickInfoStorageInputVo sickInfoStorageInputVo = new SickInfoStorageInputVo();
            sickInfoStorageInputVo.setBarcode(barcode);
            sickInfoStorageInputVo.setPhone(phone);
            sickInfoStorageInputVo.setFilePath(uri);
            sickInfoStorageService.save(sickInfoStorageInputVo);
        } catch (IOException e) {
            LOGGER.error("上传错误", e);
            return error("上传错误");
        }
        return success();
    }

    @PostMapping("/list")
    public Result list(@RequestParam String phone, @RequestParam String timestamp, @RequestParam String smsCode, @RequestParam String sign) throws BadPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, UnsupportedEncodingException, NoSuchPaddingException, InvalidKeyException {
        if (!validate(phone, timestamp, smsCode, sign)) {
            throw new BusinessException("签名校验错误");
        }
        if (!smsService.validateCode(phone, smsCode)) {
            throw new BusinessException("验证码错误");
        }
        List<SickInfoStorageOutputVo> sickInfoStorageOutputVoList = sickInfoStorageService.listByPhone(phone);
        return success(sickInfoStorageOutputVoList);
    }

    private boolean validate(String phone, String timestamp, String smsCode, String signPara) throws BadPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, UnsupportedEncodingException, NoSuchPaddingException, InvalidKeyException {
        String content = "phone=" + phone + "&" + "smsCode=" + smsCode + "&" + "timestamp=" + timestamp;
        String secData = AESUtil.encrypt(content, aesKey);
        String sign = EncryptUtils.md5(secData);
        if (sign.equals(signPara)) {
            return true;
        }
        return false;
    }
}